package com.tianji.learning.listener;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Queue.PAY_SUCCESS_QUEUE;
@Slf4j
@Component
@RequiredArgsConstructor
public class LearningListener {
    private final ILearningLessonService learningLessonService;

    /**
     * 监听订单支付成功消息
     * @param orderBasicDTO
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = PAY_SUCCESS_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void handlePaySuccess(OrderBasicDTO orderBasicDTO){
        // 健壮性判断
        if (ObjectUtil.isEmpty(orderBasicDTO) || ObjectUtil.isEmpty(orderBasicDTO.getCourseIds()) ||
        ObjectUtil.isEmpty(orderBasicDTO.getUserId())){
            log.error("订单支付消息格式异常，消息{}",orderBasicDTO);
            return;
        }
        log.info("监听到用户：{}的订单：{}的支付消息，需要添加课程：{}至课表", orderBasicDTO.getUserId(), orderBasicDTO.getOrderId(), orderBasicDTO.getCourseIds());
        learningLessonService.add(orderBasicDTO);

    }

    /**
     * 监听退款消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.LEARNING_LESSON_REFUND_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void handleRefund(OrderBasicDTO orderBasicDTO){
        // 健壮性判断
        if (ObjectUtil.isEmpty(orderBasicDTO) || ObjectUtil.isEmpty(orderBasicDTO.getCourseIds()) ||
                ObjectUtil.isEmpty(orderBasicDTO.getUserId())){
            log.error("订单退款消息格式异常，消息{}",orderBasicDTO);
            return;
        }
        log.info("监听到用户：{}的订单：{}的退款消息，需要删除课程：{}", orderBasicDTO.getUserId(), orderBasicDTO.getOrderId(), orderBasicDTO.getCourseIds());
        learningLessonService.delete(orderBasicDTO);
    }
}
